package com.caixin.domain.common;

import com.caixin.common.exception.DomainValidException;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.io.Serializable;
import java.util.Optional;
import java.util.Set;

/**
 * 聚合根
 *
 * @author wbcaicx
 * @version 1.0.0
 * @createTime 2021年12月07日 15:15
 */
@Data
@Accessors(chain = true)
public abstract class BaseAggregate<T extends Serializable> implements Serializable {

    /**
     * 主键Id
     */
    T id;

    /**
     * 出发聚合根验证
     */
    public  void valid(){
        this.valid(new Class[0]);
    }
    public  void valid(Class<?>... groups){

        Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory()
                .getValidator()
                .validate(this,groups);
        if (!CollectionUtils.isEmpty(validateSet)) {
            Optional<String> first = validateSet.stream().map(ConstraintViolation::getMessage).findFirst();
            if(first.isPresent())
            {
               throw  new DomainValidException(first.get());
            }
        }
    }
}
